package Server.ClientObj;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;

import Server.AccountSystem.AccountSystem;
import Server.RolerSystem.RolerSystem;

import Common.Constant.CommonConstant;

public class Receiver extends Thread{
	private ClientThread	c;
	private DataInputStream	dIn;
	
	private Logger logger = Logger.getLogger(Receiver.class.getName());
	
	public Receiver(ClientThread c, InputStream in){
		this.c = c;
		dIn = new DataInputStream(in);
		this.start();
	}
	
	public void run() {
		try {
			while(true){
				byte bTransModel = dIn.readByte();
				byte bFunctionTp = dIn.readByte();
				byte[] bData = new byte[dIn.available()];
				dIn.read(bData);
				chooseModel(bTransModel, bFunctionTp, bData);
			}
		} catch (IOException ex) {
			if(ex.getMessage().equals(CommonConstant.CONNECTION_RESET)){
				ClientThreadPool.getInstance().clientDisconnect(c);
				logger.fine(c.getName() + " disconnect.");
			} else {
				ex.printStackTrace();
			}
		}
	}
	
	private void chooseModel(byte bTransModel, byte bFunctionTp, byte[] bData){
		switch(bTransModel){
			case CommonConstant.TRANS_MODEL_ACCOUNT:
				AccountSystem.getInstance().entryAccountSystem(bFunctionTp, bData, c);
				break;
				
			case CommonConstant.TRANS_MODEL_ROLE:
				RolerSystem.getInstance().entryRolerSystem(bFunctionTp, bData, c);
				break;
		}
	}
}
